package com.zyg.apart.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyg.apart.mapper.LeasecontractMapper;
import com.zyg.apart.model.Leasecontract;
import com.zyg.apart.service.LeasecontractService;
import com.zyg.apart.util.Const;
import com.zyg.apart.util.DateUtil;
import com.zyg.apart.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class LeasecontractServiceImpl implements LeasecontractService {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private LeasecontractMapper leasecontractMapper;
    @Override
    public PageInfo<Map<String, Object>> getAllLC(Integer currentPage) {
        PageHelper.startPage(currentPage, Const.pageSize);
        List<Map<String,Object>> list = leasecontractMapper.getAllLC();
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Map<String,Object> getLCById(Integer id) {
        return leasecontractMapper.getLCById(id);
    }

    @Override
    public int editLC(Leasecontract leasecontract) {

        //结束时间
        String start  = sdf.format(leasecontract.getLc_contract_start_date());
        int months = leasecontract.getLc_month();
        String end = DateUtil.getEndDateByMonths(start,months);

        try {
            leasecontract.setLc_contract_start_date(sdf.parse(start));
            leasecontract.setLc_contract_end_date(sdf.parse(end));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //总额
        double total = leasecontract.getLc_rent() * months;
        leasecontract.setLc_total_rent(total);
        return leasecontractMapper.editLC(leasecontract);
    }

    @Override
    public int addLC(Leasecontract leasecontract) {
        leasecontract.setLc_contract_date(new Date());//签订时间

        leasecontract.setLc_contract_number(UUIDUtil.getUuid());//合同编号
        //结束时间
        String start  = sdf.format(leasecontract.getLc_contract_start_date());
        int months = leasecontract.getLc_month();
        String end = DateUtil.getEndDateByMonths(start,months);

        try {
            leasecontract.setLc_contract_start_date(sdf.parse(start));
            leasecontract.setLc_contract_end_date(sdf.parse(end));

        } catch (ParseException e) {
            e.printStackTrace();
        }

        //总额
        double total = leasecontract.getLc_rent() * months;
        leasecontract.setLc_total_rent(total);

        return leasecontractMapper.addLC(leasecontract);
    }

    @Override
    public int delLCById(Integer id) {
        return leasecontractMapper.delLCById(id);
    }
}
